package com.example.smartf.service.impl;

import com.example.smartf.model.mysql.Trainmodel;
import com.example.smartf.repository.mysql.TrainmodelRepository;
import com.example.smartf.service.TrainmodelService;
import javafx.beans.binding.DoubleExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.zip.DeflaterOutputStream;

@Service
public class TrainmodelServiceImpl implements TrainmodelService {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TrainmodelRepository trainmodelRepository;

    //按照deviceID 列出所有的模型信息
    @Override
    public List<Trainmodel> showTrainmodel(String deviceID){
        return trainmodelRepository.findAllByDeviceidOrderByTime(deviceID);
    }

    //删除一个模型
    @Override
    public String delTrainmodel(String modelID){
        int res = trainmodelRepository.deleteByModelid(Integer.parseInt(modelID));
        if( 1 == res ){
            logger.info("种植模型模型号：" + modelID + "删除");
            return "success";
        }else {
            return "failed";
        }
    }

    //利用模型进行预测
    @Override
    public Double modelPrediction(String modelID, String co2, String rh, String temp, String light,String lighttime , String ec, String ph) {
        Trainmodel trainmodel = trainmodelRepository.findByModelid(Integer.parseInt(modelID));
        if(trainmodel == null){
            return null;
        }
        Double res = null;

        Double CO2 = null;
        Double RH = null;
        Double TEMP =null;
        Double LIGHT =null;
        Double LIGHTTIME = null;
        Double EC =null;
        Double PH =null;


        try {
            CO2 = Double.parseDouble(co2);
            RH = Double.parseDouble(rh);
            TEMP = Double.parseDouble(temp);
            LIGHT = Double.parseDouble(light);
            LIGHTTIME = Double.parseDouble(lighttime);
            EC = Double.parseDouble(ec);
            PH = Double.parseDouble(ph);
        }catch (NumberFormatException e){
            e.printStackTrace();
            return null;
        }

        res = CO2 * trainmodel.getCo2_coefficient() +
                RH * trainmodel.getRh_coefficient() +
                TEMP * trainmodel.getTemp_coefficient() +
                LIGHT * trainmodel.getLight_coefficient() +
                LIGHTTIME * trainmodel.getLighttime_coefficient() +
                EC * trainmodel.getEc_coefficient() +
                PH * trainmodel.getPh_coefficient() +
                trainmodel.getIntercept();

        return res;
    }


}
